import java.util.*;

/**
 * 1002. 查找常用字符
 * https://leetcode-cn.com/problems/find-common-characters/
 */
public class Solutions_1002 {
    public static void main(String[] args) {
        String[] strs = {"bella", "label", "roller"};  // output: {"e", "l", "l"}
//        String[] strs = {"cool", "lock", "cook"};  // output: {"c", "o"}

        List<String> result = commonChars(strs);
        System.out.println(result);
    }

    public static List<String> commonChars(String[] A) {
        List<String> res = new ArrayList<>();
        int[] map = new int[26];
        boolean first = true;

        for (String str : A) {
            char[] arr = str.toCharArray();
            if (first) {
                // 第一次维护 map 数组时，直接记录
                for (int i = 0; i < arr.length; i++) {
                    map[arr[i] - 'a'] ++;
                }
                first = false;
            } else {
                int[] curMap = new int[26];
                // 记录当前遍历字符串中字符的个数
                for (int i = 0; i < arr.length; i++) {
                    curMap[arr[i] - 'a'] ++;
                }
                for (int i = 0; i < 26; i++) {
                    // 比较得到最小次数
                    map[i] = curMap[i] < map[i] ? curMap[i] : map[i];
                }
            }
        }

        for (int i = 0; i < 26; i++) {
            int count = map[i];
            for (int j = 0; j < count; j++) {
                res.add(String.valueOf((char)(i + 'a')));
            }
        }
        return res;
    }
}
